﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
//using ThaireInvestmentWeb.BusinessDelegate;
using Thaire.Investment.Common;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers.Instrument
{
    public class LoanController : Controller
    {
        private WcfSerivce.InvestmentServiceClient _service;
        public WcfSerivce.InvestmentServiceClient Service
        {
            get { return _service ?? (_service = ServiceFactory.GetService()); }
        }

        #region ManageLoanHeader

        public ActionResult ManageLoan()
        {
            ManageLoanModel model = null;
            try
            {
                var data = Service.GetLoanHeaderScreenData(null, true);
                model = ManageLoanModel.BuildModel(data);
            }
            catch (Exception ex)
            {
                model = new ManageLoanModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageLoanModel"] = model;
            return View("ManageLoan", model);
        }

        [HttpPost]
        public ActionResult SearchLoanHeader(ManageLoanModel model)
        {
            var oldModel = (ManageLoanModel)TempData["ManageLoanModel"];
            try
            {
                if (!String.IsNullOrEmpty(model.SearchBtn))
                {
                    var result = Service.SearchLoans(model.SearchFilter);

                    if (result == null || result.Length == 0)
                    {
                        ViewBagUtil.SetDataNotFoundInfo(ViewBag);
                    }
                    else
                    {
                        oldModel.Result = new List<LoansHeaderAdapter>();
                        foreach (var loansHeader in result)
                        {
                            oldModel.Result.Add(new LoansHeaderAdapter(loansHeader));
                        }
                    }
                }
                else if (!String.IsNullOrEmpty(model.ResetBtn))
                {
                    ModelState.Clear();
                    oldModel.ClearFilterAndData();
                }
                TempData["ManageLoanModel"] = oldModel;
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("ManageLoan", oldModel);
        }
        #endregion

        #region LoanHeader

        public ActionResult GetProvinceAutocomplete(string param)
        {
            var model = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            TempData["EditLoanHeaderModel"] = model;

            //TODO : get proviance(s) here (ไม่มี spec) 
            //var data = Service.Get...(param);
            List<string> result = new List<string> { "กรุงเทพฯ", "ร้อยเอ็ด" };
            var data = result.FindAll(x => x.Contains(param));
            return Json(data, JsonRequestBehavior.AllowGet);
            //return Json( new { SelectedProvince = "Alive" });
        }

        public ActionResult GetDistrictAutocomplete(string param)
        {
            var model = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            TempData["EditLoanHeaderModel"] = model;

            //TODO : get proviance(s) here (ไม่มี spec) 
            //var data = Service.Get...(param);
            List<string> result = new List<string> { "หนองแขม", "พระนคร" };
            var data = result.FindAll(x => x.Contains(param));
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetSubDistrictAutocomplete(string param)
        {
            var model = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            TempData["EditLoanHeaderModel"] = model;

            //TODO : get proviance(s) here (ไม่มี spec) 
            //var data = Service.Get...(param);
            List<string> result = new List<string> { "หนองแขม", "หนองค้างพลู" };
            var data = result.FindAll(x => x.Contains(param));
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetMaturityStatus(DateTime? contractEndDate)
        {
            //คำนวณจาก LOANS_HEADER.CONTRACT_END_DATE กับ System date ถ้า LOANS_HEADER.CONTRACT_END_DATE >= System Date จะแสดงว่าเป็น Alive ถ้าไม่ใช่เป็น Matured

            var model = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            TempData["EditLoanHeaderModel"] = model;
            return Json(contractEndDate.GetValueOrDefault().Date >= DateTime.Now.Date ? new { MaturityStatus = "Alive" } : new { MaturityStatus = "Matured" });
        }
        public ActionResult GetInvolvedType(int id)
        {
            var model = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            TempData["EditLoanHeaderModel"] = model;
            var involve = model.ScreenData.InvolvedPartyTypes.SingleOrDefault(x => x.InvolvedPartyTypeId == id);
            return Json(involve != null ? new { InvolvedPartyTypeReference = involve.InvolvedPartyTypeReference, InvolvedPartyTypeCode = involve.InvolvedPartyTypeCode }
                : new { InvolvedPartyTypeReference = "", InvolvedPartyTypeCode = "" });
        }

        public ActionResult EditLoanHeader(int? headerId)
        {
            EditLoanHeaderModel model = null;
            try
            {
                var data = Service.GetLoanHeaderScreenData(headerId, false);
                model = EditLoanHeaderModel.BuildModel(data);
                if (data != null && data.HeaderDTO != null)
                {
                    model.UpdateMode = true;
                    ViewBag.UpdateMode = true;

                    //if (data.HeaderDTO.LoansInterestDetails != null && data.HeaderDTO.LoansInterestDetails.Length > 0)
                    //{
                    //    model.Installment = WebUtil.FormatDecimal2Digit(scrData.Interests[0].Installment);
                    //    model.Period = scrData.Interests[0].InterestPeriod.GetValueOrDefault().ToString();
                    //}
                }
                TempData["EditLoanHeaderModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditLoanHeaderModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult EditLoanHeader(EditLoanHeaderModel model)
        {
            var oldModel = (EditLoanHeaderModel)TempData["EditLoanHeaderModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SaveBtn))
                    {
                        var co = oldModel.ScreenData.Companies.SingleOrDefault(x => x.CompanyId == model.Header.CompanyID.GetValueOrDefault());
                        if (co != null)
                            model.Header.CompanyName = co.CompanyNameTh;
                        var loanType = oldModel.LoanTypeList.SingleOrDefault(x => x.Value == model.Header.LoanTypeID.GetValueOrDefault().ToString());
                        if (loanType != null)
                            model.Header.LoanTypeName = loanType.Text;
                        var involvedPartyType = oldModel.InvolvedPartyTypeNameList.SingleOrDefault(x => x.Value == model.Header.InvolvedPartyTypeId.GetValueOrDefault().ToString());
                        if (involvedPartyType != null)
                            model.Header.InvolvedPartyTypeName = involvedPartyType.Text;
                        var occBw = oldModel.OccupationsOfBorrowerList.SingleOrDefault(x => x.Value == model.Header.BorrowerOccupationID.GetValueOrDefault().ToString());
                        if (occBw != null)
                            model.Header.BorrowerOccupationName = occBw.Text;
                        var occGt = oldModel.OccupationsOfGuarantorList.SingleOrDefault(x => x.Value == model.Header.BorrowerOccupationID.GetValueOrDefault().ToString());
                        if (occGt != null)
                            model.Header.GuarantorOcuupationName = occGt.Text;
                        var titleDeedProvinceName = oldModel.ProvinceList.SingleOrDefault(x => x.Value == model.Header.TitleDeedProvinceID.GetValueOrDefault().ToString());
                        if (titleDeedProvinceName != null)
                            model.Header.TitleDeedProvinceName = titleDeedProvinceName.Text;
                        var titleDeedDistrictName = oldModel.DistrictList.SingleOrDefault(x => x.Value == model.Header.TitleDeedDistrictID.GetValueOrDefault().ToString());
                        if (titleDeedDistrictName != null)
                            model.Header.TitleDeedDistrictName = titleDeedDistrictName.Text;
                        var titleDeedSubDistrict = oldModel.SubDistrictList.SingleOrDefault(x => x.Value == model.Header.TitleDeedSubDistrictID.GetValueOrDefault().ToString());
                        if (titleDeedSubDistrict != null)
                            model.Header.TitleDeedSubDistrictName = titleDeedSubDistrict.Text;

                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Header.LoansHeaderID = oldModel.Header.LoansHeaderID;
                            model.Header.ModifyBY = ServiceFactory.UserId;
                            model.Header.CreateBY = oldModel.Header.CreateBY;
                            model.Header.CreateDate = oldModel.Header.CreateDate;
                            model.Header.ModifyDate = oldModel.Header.ModifyDate;
                            var result = Service.UpdateLoanHeader(model.Header);
                            oldModel.Header = result.Header;
                            //todo: assign value here
                            //oldModel.Transactions = result.Transactions;
                        }
                        else
                        {
                            model.Header.CreateBY = ServiceFactory.UserId;
                            var result = Service.InsertLoanHeader(model.Header);
                            oldModel.Header = result.Header;
                            //todo: assign value here
                            //oldModel.Transactions = result.Transactions;
                        }
                        oldModel.UpdateMode = true;
                        ViewBag.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditLoanHeaderModel"] = oldModel;
            return View(oldModel);
        }

        #endregion

        #region LoanExtraIntallment

        public ActionResult EditLoanExtraIntallment(int? headerId, int? extraIntallmentId)
        {
            EditExtraInstallmentModel model = null;
            try
            {
                var data = Service.GetLoanExtraInstallmentScreenData(headerId, extraIntallmentId);
                model = EditExtraInstallmentModel.BuildModel(data);
                TempData["EditExtraInstallmentModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditExtraInstallmentModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditLoanExtraIntallment", model);
        }

        [HttpPost]
        public ActionResult EditLoanExtraIntallment(EditExtraInstallmentModel model)
        {
            var oldModel = (EditExtraInstallmentModel)TempData["EditExtraInstallmentModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Extrainstallment.LoansExtrainstallmentID =
                                oldModel.Extrainstallment.LoansExtrainstallmentID;
                            model.Extrainstallment.ModifyBY = ServiceFactory.UserId;
                            model.Extrainstallment.CreateBY = oldModel.Extrainstallment.CreateBY;
                            model.Extrainstallment.CreateDate = oldModel.Extrainstallment.CreateDate;
                            model.Extrainstallment.ModifyDate = oldModel.Extrainstallment.ModifyDate;
                            oldModel.Extrainstallment = Service.UpdateLoansExtrainstallment(model.Extrainstallment);
                        }
                        else
                        {
                            model.Extrainstallment.CreateBY = ServiceFactory.UserId;
                            oldModel.Extrainstallment = Service.InsertLoansExtrainstallment(model.Extrainstallment);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    //ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditExtraInstallmentModel"] = oldModel;
            return View("EditLoanExtraIntallment", oldModel);
        }

        #endregion

        #region LoanInterest

        public ActionResult GetInstallment(decimal newInterestRate)
        {
            var model = (LoanInterestRateModel)TempData["LoanInterestRateModel"];
            TempData["LoanInterestRateModel"] = model;
            var intmet = Calculator.CalLoanInstallment(model.LoansHeader.ContractAmount.GetValueOrDefault(), newInterestRate, model.TotalMonth);
            //var result = Math.Round(Convert.ToDouble(intmet), 2);
            return Json(new { Installment = intmet.ToString("N2") });
        }

        public ActionResult LoanInterest(int headerID)
        {
            LoanInterestRateModel model = null;
            try
            {
                LoanInterestRateScreenData scrData = Service.GetLoanInterestRateScreenData(headerID);
                model = new LoanInterestRateModel(scrData);
                model.TotalMonth = Calculator.CountDiffMonthBetweenStartAndEndDate(scrData.Header.ContractStartDate, scrData.Header.ContractEndDate).GetValueOrDefault();

                if (scrData.Interests.Length > 0)
                {
                    model.Installment = scrData.Interests[0].Installment;
                    model.Period = scrData.Interests[0].InterestPeriod.GetValueOrDefault();
                }
                else
                {
                    //model.Installment = "N/A";
                    model.Period = Calculator.CalPeriodYearAndMonth(scrData.Header.ContractStartDate, scrData.Header.ContractEndDate).GetValueOrDefault();
                }
            }
            catch (Exception ex)
            {
                model = new LoanInterestRateModel(new LoanInterestRateScreenData() { Header = new LoansHeader(), Interests = new LoansInterestDetail[0] });
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }

            model.HeaderID = headerID;
            TempData["LoanInterestRateModel"] = model;
            return View(model);
        }

        [HttpPost]
        public ActionResult LoanInterest(LoanInterestRateModel model)
        {
            var oldModel = (LoanInterestRateModel)TempData["LoanInterestRateModel"];
            oldModel.NewInterestRate = model.NewInterestRate;
            oldModel.NewMLR = model.NewMLR;
            oldModel.NewMLRMinus = model.NewMLRMinus;
            oldModel.NewMLRRateDate = model.NewMLRRateDate;
            oldModel.NewUpdateInfo = model.NewUpdateInfo;
            oldModel.Installment = model.Installment;
            if (!String.IsNullOrEmpty(model.SubmitBtn))
            {

                //if (model.UpdateMode || oldModel.UpdateMode)
                //{
                //    var detail = new LoansInterestDetail();
                //    detail.ModifyBY = SessionManager.UserID(Session);
                //    detail.InterestHeaderID = oldModel.LoansHeader.LoansHeaderID;
                //    detail.InterestRate = oldModel.NewInterestRate;
                //    detail.MlrDate = oldModel.NewMLRRateDate;
                //    detail.MlrMinus = oldModel.NewMLRMinus;
                //    detail.MlrRate = oldModel.NewMLR;
                //    detail.UpdateInfo = oldModel.NewUpdateInfo;
                //    detail.InterestPeriod = Calculator.CalPeriodYearAndMonth(oldModel.LoansHeader.ContractStartDate, oldModel.LoansHeader.ContractEndDate);
                //    detail.Installment = oldModel.Installment;
                //    Service.UpdateInterestRateDetail(detail);
                //}
                //else
                //{
                var detail = new LoansInterestDetail();
                detail.InterestHeaderID = oldModel.HeaderID;
                detail.CreateBY = SessionManager.UserID(Session);
                detail.InterestHeaderID = oldModel.LoansHeader.LoansHeaderID;
                detail.InterestRate = oldModel.NewInterestRate;
                detail.MlrDate = oldModel.NewMLRRateDate;
                detail.MlrMinus = oldModel.NewMLRMinus;
                detail.MlrRate = oldModel.NewMLR;
                detail.UpdateInfo = oldModel.NewUpdateInfo;
                detail.InterestPeriod = Calculator.CalPeriodYearAndMonth(oldModel.LoansHeader.ContractStartDate, oldModel.LoansHeader.ContractEndDate);
                detail.Installment = oldModel.Installment;

                var result = Service.InsertInterestRateDetail(detail);

                oldModel.Interest.Add(result);
                //}
                //oldModel.UpdateMode = true;
                //ViewBag.UpdateMode = true;
                ViewBagUtil.SetCompletedInfo(ViewBag);
            }
            oldModel.NewInterestRate = null;
            oldModel.NewMLR = null;
            oldModel.NewMLRMinus = null;
            oldModel.NewMLRRateDate = null;
            oldModel.NewUpdateInfo = null;
            oldModel.Installment = null;
            ModelState.Clear();
            TempData["LoanInterestRateModel"] = oldModel;
            return View(oldModel);
        }

        public ActionResult AmortizeLoanSchedule(int interestDetailID, int headerID)
        {

            AmortizeLoanScheduleModel model = null;
            try
            {
                AmortizeLoanScheduleScreenData scrData = Service.GetAmortizeLoanScheduleScreenData(interestDetailID);
                model = new AmortizeLoanScheduleModel(scrData);
            }
            catch (Exception ex)
            {
                model = new AmortizeLoanScheduleModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }

            model.HeaderID = headerID;

            return View("AmortizeLoanSchedule", model);
        }
        #endregion

    }
}
